
package com.sms.homework;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sms.fileupload.NewProject;
import com.sms.note.Note;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class Dealaddhomework extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public Dealaddhomework() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		// 返回ajax的信息
			String msg = "";
			List<Map> appendFile = null;

			// Create a factory for disk-based file items
			DiskFileItemFactory disk = new DiskFileItemFactory();
			// 当上传文件太大时，因为虚拟机能使用的内存是有限的，所以此时要通过临时文件来实现上传文件的保存
			// 此方法是设置是否使用临时文件的临界值（单位：字节）
			disk.setSizeThreshold(1024 * 5);// 设置上传缓冲区容量为5k

			String servletPath = this.getServletContext().getRealPath("/");// 获得服务器所在地址
			String tempFile = "tempFile";
			String saveFile = "uploadFile";
			String tempPath = servletPath + tempFile;//临时文件路径
			String savePath = servletPath + saveFile;//存放文件实际路径
			
			//System.out.println(path);
			File tfile = new File(tempPath);
			if (!tfile.exists()) {
				tfile.mkdirs();
			}
			
			File sfile = new File(savePath);
			if (!sfile.exists()) {
				sfile.mkdirs();
			}
			// 设置临时文件的路径（绝对路径）
			disk.setRepository(tfile);

			// 创建能够解析上传文件的二进制流的类
			ServletFileUpload sfu = new ServletFileUpload(disk);
			long maxsize = 1024 * 1024 * 100;
			sfu.setSizeMax(maxsize);// 限制最大上传容量为100M

			List<FileItem> list = null;
			try {
				list = sfu.parseRequest(request);
			} catch (FileUploadException e) {
				msg = "error";
			}

			Iterator it = null;

			try {
				it = list.iterator();
			} catch (NullPointerException e) {
				out.println("<script language='javascript'>");
				out.println("alert('不支持你所上传文件的类型')");
				out.println("</script>");
				msg = "";
			}

			if (it != null) {
				String fromID = "";				
				String title = "";
				String endtime = "";
				List<String> member = new ArrayList<String>();
				String content = "";
				appendFile = new ArrayList<Map>();
				while (it.hasNext()) {
					FileItem fileItem = (FileItem) it.next();

					if (fileItem.isFormField()) {// 为表单域
						String name = fileItem.getFieldName();
						String value = new String(fileItem.getString().getBytes("ISO-8859-1"), "utf-8");
						value.replace("\r\n", "<br>");
						//System.out.println(value);
						if (name.equals("fromID")) {
							fromID = value;
						}if (name.equals("title")) {
							title = value;
						}
						if (name.equals("endtime")) {
							endtime = value;
						}
						if (name.equals("member")) {
							member.add(value);
						}
						if (name.equals("content")) {
							content = value;
						}
					} else { // 为文件上传域
						String locPath = fileItem.getName();// 上传文件所在的本机的绝对路径
						System.out.println(locPath);
						if (!locPath.equals("")) {// 上传文件路径不为空
							Boolean isSuccess = false;
							
							// 获得上传文件的文件名
							int index = locPath.lastIndexOf("\\");
							String fileName = locPath.substring(index + 1);//文件的实际文件名，下载时候设置头信息用
							
							String saveName = "";//保存在服务器上的文件名，由日期+随机数+后缀组成
							SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
							saveName += sdf.format(new java.util.Date());
							
							for(int i=0; i<6; i++) {//得到6位10以内的随机数
								Random random = new Random();
								int r = random.nextInt(10);
								saveName += r;
							}
							
							//得到有后缀名的用来保存在服务器上的整个文件名
							index = locPath.lastIndexOf(".");
							saveName += locPath.substring(index);
							

							//long filesize = fileItem.getSize();
						

							String serverPath = savePath + "\\" + saveName;// 文件上传到服务器端的绝对路径
							File f = new File(serverPath);
							
							/*try {
								fileItem.write(f);
							} catch (Exception e) {
								e.printStackTrace();
							}*/
							
							FileOutputStream fos = new FileOutputStream(f);

							if (fileItem.isInMemory()) {
								try {
									fos.write(fileItem.get());
									isSuccess = true;
								} catch (IOException e) {
									msg = "error";
								} finally {
									fos.close();
								}
							} else {
								InputStream is = null;
								try {
									is = fileItem.getInputStream();
									int i = -1;// 文件是否读完标志
									byte[] b = new byte[1024];
									i = is.read(b);
									while (i > 0) {
										fos.write(b, 0, i);
										i = is.read(b);
									}
									isSuccess = true;
								} catch (IOException e) {
									msg = "error";
								} finally {
									is.close();
									fos.flush();
									fos.close();
								}
							}
							
							
							//System.out.println(isSuccess + msg);
							if (isSuccess && !msg.equals("error")) {
								
								Map<String, String> map = new HashMap<String, String>();
								map.put("fileName", fileName);
								map.put("saveName", saveName);
								appendFile.add(map);
								//System.out.println("有附件");
							} else {
								msg = "error";
							}
						}//上传为文件路径不为空结束

					}//上传 为文本域结束
				}//while结束
				/*System.out.println(fromID);
				System.out.println(title);
				System.out.println(endtime);
				System.out.println(content);
				if(title.equals("")){
					
					
				}
				*/
				//插入数据库关于新项目的信息
				boolean isSuccess = new Homework().inData(fromID, title, endtime,member, content, appendFile);
				if(isSuccess) {
					msg = "ok";
				} else {
					msg = "error";
				}
			}
			
			
			msg.replace("/rn/g", "");
			if(msg.equals("ok")) {
				out.println("<script language='javascript'>");
				out.println("alert('ok')"); 
				out.println("parent.callback('ok')"); 
				out.println("</script>");
			} else {
				out.println("<script language='javascript'>");
				out.println("alert('error')");
				out.println("parent.callback('error')");   
				out.println("</script>");
			}
			
			out.flush();
			out.close();
			//System.out.println(msg);
			//out.write(msg);
		}
	}
